<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\SelectPresenter;
use App\Admin\Models\Administrator;
use App\Admin\Repositories\WorkOrderDispatch;
use App\Models\ProcessesArchive;
use App\Models\WorkOrder;
use App\Models\WorkOrderComponent;
use App\Models\Workshop;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Admin\Extensions\equalSelect;

class WorkOrderDispatchController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(WorkOrderDispatch::with(['workOrder']), function (Grid $grid) {
            $grid->model()->where('processes_archives_id', '<', 11);
            $grid->model()->orderBy('id', 'desc');

            $grid->column('id')->sortable();
            $grid->column('end_at', admin_trans('work-order-dispatch.fields.end_at'))->display(function () {
                if ($this->actual_end_at) {
                    return date('Y-m-d', strtotime($this->actual_end_at));
                }
                return '';
            });
            $grid->column('service_advisor', admin_trans('work-order-dispatch.fields.service_advisor'))->display(function () {
                return $this->workOrder->serviceAdvisor->name;
            });
            $grid->column('user_name');
            $grid->column('workshop', admin_trans('work-order-dispatch.fields.workshop'))->display(function () {
                return $this->workOrder->workshop->title;
            });
            $grid->column('car_number', admin_trans('work-order-dispatch.fields.car_number'))->display(function () {
                return $this->workOrder->car_number;
            });
            $grid->column('car_frame', admin_trans('work-order-dispatch.fields.car_frame'))->display(function () {
                return $this->workOrder->car_frame;
            });
            $grid->column('work_order_sn', admin_trans('work-order-dispatch.fields.work_order_sn'))->display(function () {
                return $this->workOrder->order_sn;
            });
            $grid->column('car', admin_trans('work-order-dispatch.fields.car'))->display(function () {
                return $this->workOrder->car->title;
            });
            $grid->column('order_remark', admin_trans('work-order-dispatch.fields.order_remark'))->display(function () {
                return $this->workOrder->remark;
            });
            $grid->column('processes_archives_title');
            $grid->column('performance_quantity_base', admin_trans('work-order-dispatch.fields.performance_quantity_base'))->display(function () {
                return WorkOrderComponent::where('work_order_id', $this->work_order_id)->sum('performance_quantity_base');
            });
            $grid->column('standard_quantity_base', admin_trans('work-order-dispatch.fields.standard_quantity_base'))->display(function () {
                return WorkOrderComponent::where('work_order_id', $this->work_order_id)->sum('standard_quantity_base');
            });
            $grid->column('standard_working_base', admin_trans('work-order-dispatch.fields.standard_working_base'))->display(function () {
                return WorkOrderComponent::where('work_order_id', $this->work_order_id)->sum('standard_working_base');
            });
            $grid->column('performance_working_base', admin_trans('work-order-dispatch.fields.performance_working_base'))->display(function () {
                return WorkOrderComponent::where('work_order_id', $this->work_order_id)->sum('performance_working_base');
            });

            $grid->column('actual_start_at');
            $grid->column('actual_end_at');
            $grid->column('expect_end_at');

            $grid->column('component', admin_trans('work-order-dispatch.fields.component'))->display(function () {
                $component =  WorkOrderComponent::where('work_order_id', $this->work_order_id)->get();
                $component_title = '';

                if ($component) {
                    foreach ($component as $key => $value) {
                        $component_title .= $value['title'].',';
                    }
                }

                return $component_title;
            });

            $grid->column('updated_at')->sortable();
        
            $grid->filter(function (Grid\Filter $filter) {
                $filter->between('actual_start_at')->datetime();
                $filter->between('actual_end_at')->datetime();
                $filter->between('workOrder.settlement_at', admin_trans('work-order-dispatch.fields.settlement_at'))->datetime();
                $filter->like('workOrder.car_number', admin_trans('work-order-dispatch.fields.car_number'));
                $processes_archive = ProcessesArchive::where('id', '<', 11)->pluck('title', 'id');
                $filter->equal('processes_archives_id', admin_trans('work-order-dispatch.fields.processes_archives_title'))->select($processes_archive);

                $workshop = Workshop::all()->pluck('title', 'id');
                $filter->equal('workOrder.workshop_id', admin_trans('work-order-dispatch.fields.workshop'))->select($workshop)->default(1)->load('user_id', 'technician-list');
                $filter->equal('user_id', admin_trans('work-order-dispatch.fields.user_name'))->select([]);
                $service_advisor = Administrator::whereHas('roles', function($query) {
                    $query->where('role_id', 3);
                })->pluck('name', 'id');
                $filter->equal('order.service_advisor_id', admin_trans('work-order-dispatch.fields.service_advisor'))->select($service_advisor);
            });

            $grid->fixColumns(0, -0);

            // 启用异步渲染以提高性能，特别是在处理大量数据时
            $grid->async();

            // 设置表格底部显示统计信息
            $grid->footer(function ($collection) use ($grid) {
                // 获取当前表格查询构建器并应用所有查询条件（包括筛选）
                $query = \App\Models\WorkOrderDispatch::query();

                // 获取 Grid 模型已应用的所有查询条件（包括筛选器）
                $grid->model()->getQueries()->unique()->each(function ($value) use (&$query) {
                    // 跳过不需要的方法，如分页、排序等
                    if (in_array($value['method'], ['paginate', 'get', 'orderBy', 'orderByDesc'], true)) {
                        return;
                    }
                    // 应用查询条件
                    $query = call_user_func_array([$query, $value['method']], $value['arguments'] ?? []);
                });

                // 执行聚合查询，计算总和
                $stats = $query
                    ->join('work_order_components', 'work_order_dispatchs.work_order_id', '=', 'work_order_components.work_order_id')
                    ->select(
                    DB::raw('SUM(work_order_components.performance_quantity_base) as total_performance_count'),
                    DB::raw('SUM(work_order_components.standard_quantity_base) as total_standard_count'),
                    DB::raw('SUM(work_order_components.standard_working_base) as total_standard_hours'),
                    DB::raw('SUM(work_order_components.performance_working_base) as total_performance_hours')
                )->first(); // 获取第一条记录，即汇总记录

                // 构建统计信息的 HTML
                $html = <<<HTML
<div style="padding: 10px; background-color: #f8f9fa; border-top: 1px solid #ddd; font-weight: bold;text-align: center">
    <span style="margin-right: 20px;">绩效件数总和: {$stats->total_performance_count}</span>
    <span style="margin-right: 20px;">标准件数总和: {$stats->total_standard_count}</span>
    <span style="margin-right: 20px;">标准工时总和: {$stats->total_standard_hours}</span>
    <span>绩效工时总和: {$stats->total_performance_hours}</span>
</div>
HTML;

                return $html;
            });

            $grid->disableDeleteButton();
            $grid->disableViewButton();
            $grid->disableEditButton();
            $grid->disableCreateButton();
        });
    }

    public function technicianList(Request $request)
    {
        $param = $request->all();

        $technician = Administrator::whereHas('roles', function($query) {
            $query->where('role_id', 2);
        })->where('workshop_id', $param['q'])->get(['id', DB::raw('name as text')]);

        return $technician;
    }

    public function serviceAdvisorList(Request $request)
    {
        $param = $request->all();

        $service_advisor = Administrator::whereHas('roles', function($query) {
            $query->where('role_id', 3);
        })->where('workshop_id', $param['q'])->get(['id', DB::raw('name as text')]);

        return $service_advisor;
    }
}
